package shared;

import java.io.*;
import java.util.*;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.*;

/**
 * cal contains a lists of user and task objects
 * 
 * When converted to XML the structure will be:
	<users>
		<user>
			<name></name>
			<password></password>
		</user>
	</users>
 * @author Peter
 *
 */

@SuppressWarnings("serial")
@XmlRootElement(name = "cal")
public class Cal implements Serializable{	
	@XmlElementWrapper(name = "users")
    @XmlElement(name = "user")
    public List<User> users;

	@XmlElementWrapper(name = "tasks")
    @XmlElement(name = "task")
    public List<Task> tasks;
	
	public Cal() {
		users = new ArrayList<User>();
		tasks = new ArrayList<Task>();
	}
	
	public static Cal createCal(String path) throws JAXBException, FileNotFoundException {	
		//Create stream from path
        FileInputStream stream = new FileInputStream(path); 
        
        //Return Cal object using overloaded method
    	return createCal(stream);
    }
	
	public static Cal createCal(InputStream stream) throws JAXBException, FileNotFoundException {
		//Create context
    	JAXBContext jaxbContext = JAXBContext.newInstance(Cal.class);	
    	
    	//Return deserialized data
    	return (Cal) jaxbContext.createUnmarshaller().unmarshal(stream);	
    }
	
	public static String createXML(Cal cal) throws JAXBException, IOException {
		//Create writer
		StringWriter writer = new StringWriter();
		
		//Create context
    	JAXBContext jaxbContext = JAXBContext.newInstance(Cal.class);
    	
    	//Create and setup marshaller
        Marshaller marshaller= jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        
        //Marshal Cal object to writer and return string
        marshaller.marshal(cal, writer);        
		return writer.toString();
	}
	
	public static String serialize(Cal cal) throws JAXBException, IOException {
		//Create writer
		StringWriter writer = new StringWriter();
		
		//Create context
    	JAXBContext jaxbContext = JAXBContext.newInstance(Cal.class);
    	
    	//Create and setup marshaller
        Marshaller marshaller= jaxbContext.createMarshaller(); 
        
        //Marshal Cal object to writer and return string
        marshaller.marshal(cal, writer);        
		return writer.toString();
	}
    
    public static void saveCal(Cal cal, String path) throws JAXBException, IOException {
    	//Create file and writer
    	File file = new File(path);        
    	BufferedWriter output = new BufferedWriter(new FileWriter(file));
    	
    	//Output serialized Cal object
        output.write(createXML(cal));
        output.close();
    }
}




